package com.crazymakercircle.jvm;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class JvmMem {

  @Test
  public void heapTest() {
    List<Integer> list = new ArrayList<>();

    while (true) {
      list.add(1);
    }
  }

  public void recursiveMethod() {
    recursiveMethod();
  }

  @Test
  public void stackTest() {
    recursiveMethod();
  }

  static class OOM{}
  @Test
  public void metaspaceOverflowTest() {
    int i = 0;//模拟计数多少次以后发生异常
    try {
      while (true){
        i++;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(OOM.class);
        enhancer.setUseCache(false);
        enhancer.setCallback(new MethodInterceptor() {
          @Override
          public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            return methodProxy.invokeSuper(o, new String[]{});
          }
        });
        enhancer.create();
      }
    } catch (Throwable e) {
      System.out.println("=================多少次后发生异常："+i);
      e.printStackTrace();
    }
  }

  @Test
  public void fullGcTest() {

    try {
      while (true) {
        List<byte[]> list = new ArrayList<>();
        for (int i = 0 ; i< 2; i++) {
          byte[] bytes = new byte[10 * 1024 * 1024]; // 分配10MB的内存
          list.add(bytes);
          Thread.sleep(1000); // 每次分配后暂停1秒
        }
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
}

